<template>
  <a-card>
    <template #title>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :md="6" :xs="24" v-permiss="['select-merchant']">
            <a-form-item :label="$t('充值商户')">
              <a-select v-model:value="page.mchId" allowClear>
                <a-select-option v-for="item in merchantList" :key="item.mchId" :value="item.mchId">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('平台订单号')">
              <a-input v-model:value="page.platOrderId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('收款账号')">
              <a-input v-model:value="page.vaNumber"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('标识符')">
              <a-input v-model:value="page.identifier"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('充值方式')">
              <a-select v-model:value="page.type" allowClear>
                <a-select-option :value="1">{{ $t('线下') }}</a-select-option>
                <a-select-option :value="0">{{ $t('线上') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('状态')">
              <a-select v-model:value="page.status" allowClear>
                <a-select-option :value="1">{{ $t('成功') }}</a-select-option>
                <a-select-option :value="0">{{ $t('失败') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('充值时间')">
              <a-range-picker style="width: 100%" v-model:value="page.rechargeTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('到账时间')">
              <a-range-picker style="width: 100%" v-model:value="page.arrivalTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="text-align: right;margin-bottom: 10px">
      <a-button @click="exportExcel" :loading="exportLoading" v-permiss="['export']">{{ $t('导出') }}</a-button>
      <a-button type="primary" style="margin-left: 10px" @click="handleOnline" v-permiss="['online']">{{
          $t('线上充值')
        }}
      </a-button>
      <a-button type="primary" style="margin-left: 10px" @click="handleOffline" v-permiss="['offline']">{{
          $t('线下充值')
        }}
      </a-button>
    </div>
    <a-table :data-source="tableData" :loading="tableLoading" :pagination="pagination" :columns="tableColumn"
             :scroll="{x:true,y:600}">
      <template #imgUrl="{record}">
        <a-image v-if="record.voucherUrl" style="height: 100px" :src="record.voucherUrl"></a-image>
      </template>
    </a-table>
    <!--  线上充值-->
    <a-modal v-model:visible="onlineVisible" :footer="false" :title="$t('线上充值')">
      <a-form :model="onlineForm" :label-col="{span:4}">
        <a-form-item :label="$t('银行名称')">
          {{ onlineForm.bankName }}
        </a-form-item>
        <a-form-item :label="$t('收款人名称')">
          {{ onlineForm.name }}
        </a-form-item>
        <a-form-item :label="$t('收款账号')">
          {{ onlineForm.acc }}
        </a-form-item>
      </a-form>
    </a-modal>
    <!--  线下充值-->
    <a-modal v-model:visible="offlineVisible" :title="$t('线下充值')" @ok="offlineConfirm" :after-close="offlineClearForm"
             :confirm-loading="offlineLoading"
    >
      <a-form :model="offlineForm" :rules="offlineRulesForm" ref="offlineRef">
        <a-form-item :label="$t('银行名称')" name="bankName">
          <a-input v-model:value="offlineForm.bankName"/>
        </a-form-item>
        <a-form-item :label="$t('收款账号')">
          <a-input v-model:value="offlineForm.vaNumber"/>
        </a-form-item>
        <a-form-item :label="$t('账户名称')">
          <a-input v-model:value="offlineForm.accName"/>
        </a-form-item>
        <a-form-item :label="$t('充值商户')" name="mchId"
        >
          <a-select v-model:value="offlineForm.mchId">
            <a-select-option v-for="item in merchantList" :key="item.mchId" :value="item.mchId">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('充值金额')" name="payAmount"
        >
          <a-input v-model:value="offlineForm.payAmount" oninput="value = value.replace(/[^\d]/g, '')"/>
        </a-form-item>
        <a-form-item :label="$t('上传凭证')">
          <a-upload
              name="avatar"
              list-type="picture-card"
              :custom-request="uploadOfflineImg"
              :show-upload-list="false"
              accept="image/*"
          >
            <img v-if="offlineForm.imgUrl" :src="offlineForm.imgUrl" style=" width: 100%; height: 100%;" alt="avatar"/>
            <div v-else>
              <plus-outlined></plus-outlined>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import {onMounted, reactive, ref, toRefs, computed} from "vue";
import {selectMerchant} from "../../../api";
import {
  fetchRechargeList,
  onlineRecharge,
  uploadImage,
  offlineRecharge,
  rechargeListExport
} from "../../../api/capital";
import {export_json_to_excel} from "../../../utils/exportExcel";
import i18n from "../../../locale";
import {hasPermission} from "../../../utils/permiss";

const $t = i18n.global.t
import {PlusOutlined} from '@ant-design/icons-vue'
import {message} from "ant-design-vue";
import {formatMoney} from "../../../utils";

const tableColumn = [
  {title: $t('平台订单号'), dataIndex: 'platOrderId', fixed: 'left', width: 150, align: 'center'},
  {title: $t('交易流水号'), dataIndex: 'transactionNumber', width: 100, align: 'center'},
  {title: $t('银行名称'), dataIndex: 'bankName', width: 100, align: 'center'},
  {title: $t('收款账号'), dataIndex: 'vaNumber', width: 100, align: 'center'},
  {
    title: $t('充值商户'),
    dataIndex: 'mchName',
    width: 100,
    align: 'center',
  },
  {
    title: $t('充值金额'), dataIndex: 'payAmount', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('手续费'), dataIndex: 'fee', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('手续费扣除方式'), dataIndex: 'feeType', width: 150, align: 'center', customRender: ({text}) => {
      return text === 1 ? $t('手续费另计') : $t('从充值金额扣除')
    }
  },
  {
    title: $t('到账金额'), dataIndex: 'entryAmount', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('充值方式'), dataIndex: 'type', width: 100, align: 'center', customRender: ({text}) => {
      return text === 0 ? $t('线上') : $t('线下')
    }
  },
  {
    title: $t('状态'), dataIndex: 'status', width: 100, align: 'center', customRender: ({text}) => {
      return text === 1 ? $t('成功') : $t('失败')
    }
  },
  {title: $t('标识符'), dataIndex: 'identifier', width: 150, align: 'center'},
  {title: $t('充值时间'), dataIndex: 'createTime', width: 200, align: 'center'},
  {title: $t('到账时间'), dataIndex: 'completionTime', width: 200, align: 'center'},
  {
    title: $t('凭证'), dataIndex: 'voucherUrl', width: 150, align: 'center', slots: {
      customRender: 'imgUrl'
    }
  },
]
export default {
  name: "RechargeList",
  components: {PlusOutlined},
  setup() {
    const offlineRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      merchantList: [],
      tableData: [],
      onlineVisible: false,
      onlineForm: {},
      offlineVisible: false,
      offlineForm: {},
      offlineRulesForm: {
        mchId: {required: true, message: $t('请选择'), trigger: 'blur', type: 'number'},
        payAmount: [{required: true, message: $t('不能为空'), trigger: 'blur'},
          {
            required: true, validator: (rule, value) => {
              if (parseInt(value) < 1) {
                return Promise.reject($t('转账金额不能小于1'))
              }
              return Promise.resolve()
            }, trigger: 'blur'
          }],
      },
      exportLoading: false,
      tableLoading: false,
      offlineLoading: false,
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + $t('条'),
      onChange: (value) => {
        state.page.pageNum = value
        methods.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        methods.getTableData()
      }
    }))
    const methods = {
      async getTableData() {
        state.tableLoading = true
        const [startTime, endTime] = state.page.rechargeTime || []
        const [completionStartTime, completionEndTime] = state.page.arrivalTime || []
        const params = {
          completionStartTime, completionEndTime, startTime, endTime,
          ...state.page,
          rechargeTime: undefined,
          arrivalTime: undefined
        }
        const res = await fetchRechargeList(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.page.total = total
          state.tableData = list
          state.tableLoading = false
        } else {
          state.tableLoading = false
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        methods.getTableData()
      },
      validatorAmount(rule, value) {
        if (!value) {
          return Promise.reject($t('不能为空'))
        } else if (parseInt(value) < 10) {
          return Promise.reject($t('最低充值金额不能小于10'))
        }
        return Promise.resolve()
      },
      // 线上充值
      async handleOnline() {
        const res = await onlineRecharge()
        if (res.code === 200) {
          state.onlineVisible = true
          state.onlineForm = res.data
        }
      },
      handleOffline() {
        state.offlineVisible = true
      },
      //线下充值提交
      offlineConfirm() {
        offlineRef.value.validate().then(async () => {
          state.offlineLoading = true
          const res = await offlineRecharge(state.offlineForm)
          if (res.code === 200) {
            message.success($t('充值成功'))
            state.offlineVisible = false
            state.offlineLoading = false
            methods.getTableData()
          } else {
            state.offlineLoading = false
          }
        })
      },
      offlineClearForm() {
        state.offlineForm = {}
        offlineRef.value.resetFields()
      },
      async exportExcel() {
        state.exportLoading = true
        const [startTime, endTime] = state.page.rechargeTime || []
        const [completionStartTime, completionEndTime] = state.page.arrivalTime || []
        const params = {
          completionStartTime, completionEndTime, startTime, endTime,
          ...state.page,
          rechargeTime: undefined,
          arrivalTime: undefined
        }
        const res = await rechargeListExport(params)
        if (res.code === 200) {
          const headerData = state.tableColumn.filter(item => !item.isHide && item.title !== $t('操作'))
          const column = headerData.map(item => item.title)
          const filterVal = headerData.map(item => item.dataIndex)
          const list = [...res.data].map((item) => {
            item.type = item.type === 0 ? $t('线上') : $t('线下')
            item.status = item.status === 1 ? $t('成功') : $t('失败')
            return item;
          }).map((v) => filterVal.map((j) => v[j]));
          const fileName = $t("充值列表");
          export_json_to_excel({
            header: column,
            data: list,
            filename: fileName,
          });
          state.exportLoading = false
        } else {
          state.exportLoading = false
        }
      },
      async uploadOfflineImg(data) {
        const hide = message.loading($t('上传中...'), 0)
        const formData = new FormData()
        formData.append('file', data.file)
        const res = await uploadImage(formData)
        if (res.code === 200) {
          state.offlineForm.imgUrl = res.data
          hide()
        } else {
          hide()
        }
      },
    }
    onMounted(() => {
      selectMerchant().then(res => {
        state.merchantList = res
      })
      methods.getTableData()
    })
    return {
      offlineRef,
      pagination,
      tableColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
